package com.hjt.utils;

import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Slf4j
public class FileUtil {

    public static File saveFile(String path, String fileName, byte[] bytes) {
        File file = new File(path + File.separator + fileName);
        if (!file.getParentFile().exists()) {
            boolean mkdirs = file.getParentFile().mkdirs();
            if (!mkdirs) {
                log.error("create path fail 【{}】", file.getParentFile().getAbsoluteFile());
                throw new RuntimeException("create path fail");
            }
        }
        if (!file.exists()) {
            try {
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    log.error("create file fail 【{}】", file.getAbsoluteFile());
                    throw new RuntimeException("create file fail");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(bytes);
        }catch(Exception e) {
            throw new RuntimeException(e);
        }finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
}
